import streamlit as st
import pandas as pd
import aiohttp
import asyncio 
import json
import plotly.express as px

st.set_page_config(
    page_title="Li's Cool Fol App",
    page_icon="🧊",
    layout="wide",
    initial_sidebar_state="expanded",
)

async def fitch_data(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            data = await response.text()
            return data

async def fitch_df(url):
    data = await fitch_data(url)
    df = pd.read_json(json.loads(data))
    return df

async def query_fol_status(code):
    fol_status = await fitch_data(f"http://restfulapp:8000/fund/status/{code}")
    return fol_status

async def handler_single(data1, data2):
    df = await fitch_df(f'http://restfulapp:8000/{data1}/{data2}')
    df_extend = [await query_fol_status(code) for code in df.代码.tolist()]
    df['申赎状态'] = df_extend
    df = df.loc[-df.申赎状态.astype(str).str.contains('暂停申购|场内交易')]
    df.drop('申赎状态',axis=1,inplace=True)
    st.dataframe(df.style.highlight_max(axis=0))
    st.markdown("---")
    df['codes'] = df.apply(lambda r: str(r['代码']) + ' - '+ str(r['名称']) ,axis=1)
    codes = df.codes.tolist()
    if codes:
        option = st.selectbox(
            '选择基金代码:',
            codes)
        await draw_curve(option.split(' ')[0])


async def draw_curve(code:str):
    data = await fitch_data(f"http://restfulapp:8000/fol/history/{code}")
    history = json.loads(json.loads(data))
    history = history.get('data')
    history_df = pd.DataFrame(data=history,columns=['日期','价格','净值','溢价率'])
    history_df.日期 = pd.to_datetime(history_df.日期)
    history_df.sort_values('日期',ascending=False,inplace=True)
    for column in ['价格','净值','溢价率']:
        history_df[column] = history_df[column].astype(float)
    col1, col2 = st.columns(2)
    with col1:
        fig = px.area(history_df, x='日期', y=['溢价率'])
        st.plotly_chart(fig,theme="streamlit",use_container_width=True)
        
    with col2:
        fig = px.line(history_df, x='日期', y=['价格','净值'])
        st.plotly_chart(fig,theme="streamlit",use_container_width=True)

# async def handler():
#     await handler_single("fol","interal")
#     await handler_single("qdii","eur")
#     await handler_single("qdii","asia")

def page1():
    asyncio.run(handler_single("fol","interal"))

def page2():
    asyncio.run(handler_single("qdii","eur"))

def page3():
    asyncio.run(handler_single("qdii","asia"))

pages = {
    "FOL 国内":page1,
    "QDII 欧洲":page2,
    "QDII 亚洲":page3
}

st.sidebar.title("切换基金类型")
selection = st.sidebar.radio("", list(pages.keys()))
page = pages[selection]
page()

# asyncio.run(handler())

